package CelestialWeb;

import CelestialDataAccess.Product;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

import CelestialDataAccess.*;
import CelestialDataStructures.*;

public class InventoryServlet extends HttpServlet {

    private WriteXMLError m_WriteError = new WriteXMLError();
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
            response.setContentType("text/xml");
            response.setHeader("Cache-control", "no-cache");
            PrintWriter pw = response.getWriter();
            String strProductID;
            String strProductName;
            String strProductC;
            String strProductD;
            String strProductM;
            String strProductP;
            String strProductU;
       int searchOption = Integer.parseInt(request.getParameter("searchOption"));

       ProductsDataAccess daProducts = new ProductsDataAccess();
        Product prod;
       switch (searchOption) {
           case 1:strProductID = request.getParameter("prod_id");
               try{ //System.out.println("option 1");

                prod = daProducts.getProductByID(strProductID);
                   }catch(DataAccessException ex){
                  return ;
              }
              if(prod==null){
                 m_WriteError.writeSingleError(2, "No product records found for " + strProductID, pw);
                  return;
                }
        /* no errors, write XML data now */
        pw.write("<Products>");
        pw.write("<Product>");
        pw.write("<ProductID>" + prod.getProductID() + "</ProductID>");
        pw.write("<ProductName>" + prod.getProductName() + "</ProductName>");
        pw.write("<Cart>" + prod.getCategory() + "</Cart>");
        pw.write("<Price>" + prod.getPrice() + "</Price>");
        pw.write("<Units>" + prod.getUnits() + "</Units>");
        pw.write("</Product>");
        pw.write("</Products>");

        break;

   //search by catogery
           case 2:strProductID = request.getParameter("prod_id");
       List<Product> lst = new ArrayList<Product>();
       Iterator<Product> it;
        if(strProductID==null){
            m_WriteError.writeSingleError(1, "No Product ID is supplied", pw);
            return;
        }
        try{daProducts.getProductsByCategory(strProductID, lst);
            it = lst.iterator();
            }catch(DataAccessException ex){
            m_WriteError.writeSingleError(16384, ex.getMessage(), pw);
            return;
        }
        if(it==null){
            m_WriteError.writeSingleError(2, "No product records found for " + strProductID, pw);
            return;
        }

        /* no errors, write XML data now */
        pw.write("<Products>");
        while(it.hasNext())
        {
                prod = it.next();
                //System.out.println(prod.getProductID());

        pw.write("<Product>");
        pw.write("<ProductID>" + prod.getProductID() + "</ProductID>");
        pw.write("<ProductName>" + prod.getProductName() + "</ProductName>");
        pw.write("<Cart>" + prod.getCategory() + "</Cart>");
        pw.write("<Price>" + prod.getPrice() + "</Price>");
        pw.write("<Units>" + prod.getUnits() + "</Units>");
        pw.write("</Product>");
        }

        pw.write("</Products>");

       break;
       //delete product
           case 3: strProductID = request.getParameter("prod_id");
                   String[] temp=strProductID.split("-");
                   pw.write("<delete>");
                   System.out.println("<delete>");
                   for (int i=0;i<temp.length;i++){try {
                        temp[i]=temp[i].substring(9);
                       //System.out.println(temp[i]);
                       if (daProducts.deleteProduct(temp[i])!=1){
                           System.out.println("<myDeleteError>"+temp[i]+" Delete failed </myDeleteError>");
                           pw.write("<myDeleteError>"+temp[i]+" Delete failed </myDeleteError>");
                            } else { System.out.println("<myDeleteError>"+temp[i]+" Delete Successfully </myDeleteError>");
                              pw.write("<myDeleteError>"+temp[i]+" Delete Successfully </myDeleteError>");
                              pw.write("<deleteId>"+temp[i]+"</deleteId>");}
                   }
                   catch(DataAccessException ex){
                       pw.write("<myDeleteError>"+temp[i]+" Delete failed </myDeleteError>");
                       System.out.println("<myDeleteError>"+ ex.getMessage() +"</myDeleteError>");

                }

                   }
                   System.out.println("</delete>");
                       pw.write("</delete>");
                       pw.close();
           break;
           //display product
           case 4:strProductID = request.getParameter("prod_id");
                  prod=null;
                  pw.write("<Products>");
                try{prod = daProducts.getProductByID(strProductID.substring(7));
                   pw.write("<Product>");
        pw.write("<ProductID>" + prod.getProductID() + "</ProductID>");
        pw.write("<ProductName>" + prod.getProductName() + "</ProductName>");
        pw.write("<Cart>" + prod.getCategory() + "</Cart>");
        pw.write("<Price>" + prod.getPrice() + "</Price>");
        pw.write("<Units>" + prod.getUnits() + "</Units>");
        pw.write("<Description>" + prod.getDescription() + "</Description>");
        pw.write("<Material>" + prod.getMaterials() + "</Material>");
        pw.write("</Product>");

                   }catch(DataAccessException ex){
                   pw.write("<myError>  ex.getMessage() </myError>");
                    }
                  finally {pw.write("</Products>");}
                 /* no errors, write XML data now */

        break;
         //update product
           case 5: strProductID = request.getParameter("prod_id");
                   strProductName = request.getParameter("prod_name");
                   strProductC = request.getParameter("prod_cart");
                   strProductD = request.getParameter("prod_d");
                   strProductM = request.getParameter("prod_m");
                   strProductP = request.getParameter("prod_p");
                   strProductU = request.getParameter("prod_u");

                  try{ prod = daProducts.getProductByID(strProductID);
                       prod.setProductName(strProductName);

                       prod.settCategory(strProductC);
                       prod.setDescription(strProductD);
                       prod.setMaterials(strProductM);
                       prod.setPrice(Double.parseDouble(strProductP));
                       prod.setUnits(Integer.parseInt(strProductU));
                        System.out.println(strProductID);
                    if (daProducts.updateProduct(prod)!=1)
                        pw.print("<myUpdateError> Add Failed</myUpdateError>");
                    else pw.print("<myUpdateError> Successfully</myUpdateError>");
                   }catch(DataAccessException ex){
                      pw.write("<myUpdateError>"+ex.getMessage()+"</myUpdateError>");
                     System.out.println("<myUpdateError>"+ex.getMessage()+"</myUpdateError>");
                     }
                   finally{                pw.close();}



               break;
  //insert product
           case 6: strProductID = request.getParameter("prod_id");
                   strProductName = request.getParameter("prod_name");
                   strProductC = request.getParameter("prod_cart");
                   strProductD = request.getParameter("prod_d");
                   strProductM = request.getParameter("prod_m");
                   strProductP = request.getParameter("prod_p");
                   strProductU = request.getParameter("prod_u");

                  prod=new Product(strProductID);

                  prod.setProductName(strProductName);
                  prod.settCategory(strProductC);
                  prod.setDescription(strProductD);
                  prod.setMaterials(strProductM);
                  prod.setPrice(Double.parseDouble(strProductP));
                  prod.setUnits(Integer.parseInt(strProductU));
                  prod.setActive(true);
                 try{
                    if (daProducts.insertProduct(prod)!=1)
                        pw.write("<myError> Add Failed</myError>");
                       else pw.write("<myError> Add Successfully</myError>");
                     }catch(DataAccessException ex){
                  pw.write("<myError>"+ex.getMessage()+"</myError>");
               }finally  { pw.close();
                  
              }
                  break;


            default: break;
        }


    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
